<template>
  <view class="container position-relative">
    <view style="margin-bottom: 130rpx">
      <view class="section-1">
        <!-- 外卖配送 点餐自取 -->
        <!-- 	<template v-if="store.distance > 0 && ('takeout'===orderType || 'takein'===orderType)">
					<list-cell class="location">
						<view class="flex-fill d-flex justify-content-between align-items-center">
							<view class="store-name flex-fill">{{ orderType === 'takeout' ? '外卖配送' : '点餐自取' }}
							</view>
							<uv-switch activeColor="#dd524d" v-model="active" @change="takout">
							</uv-switch>
						</view>
					</list-cell>
				</template> -->

        <template v-if="'takeout' === orderType || 'franchisees' === orderType">
          <list-cell @click="chooseAddress">
            <view v-if="address.realName" class="w-100 d-flex flex-column">
              <view
                class="d-flex align-items-center justify-content-between mb-10"
              >
                <view class="font-size-lg text-color-base">
                  {{ address.address + " " + address.detail }}
                </view>
                <image
                  src="/static/images/navigator-1.png"
                  class="arrow"
                ></image>
              </view>
              <view
                class="d-flex text-color-assist font-size-sm align-items-center"
              >
                <view class="mr-10">{{ address.realName }}</view>
                <view>{{ address.phone }}</view>
              </view>
            </view>
            <view
              v-else
              class="flex-fill d-flex justify-content-between align-items-center"
            >
              <view class="store-name flex-fill">选择收货地址</view>
              <image src="/static/images/navigator-1.png" class="arrow"></image>
            </view>
          </list-cell>
        </template>
      </view>

      <view class="section-1" v-if="orderType !== 'franchisees'">
        <template>
          <list-cell class="location" v-if="orderType === 'counter_ordering'">
            <view
              class="flex-fill d-flex justify-content-between align-items-center"
            >
              <view class="store-name flex-fill">{{ store.name || '' }}</view>
              <image src="/static/images/navigator-1.png" class="arrow"></image>
            </view>
          </list-cell>
          <list-cell class="location" @click="goToShop" v-else>
            <view
              class="flex-fill d-flex justify-content-between align-items-center"
            >
              <view class="store-name flex-fill">{{ store.name || '' }}</view>
              <image src="/static/images/navigator-1.png" class="arrow"></image>
            </view>
          </list-cell>
        </template>

        <template>
          <list-cell arrow class="meal-time" v-if="orderType == 'takein'">
            <view
              class="flex-fill d-flex justify-content-between align-items-center"
              @click="takeinTIme = !takeinTIme"
            >
              <view class="title">取餐时间</view>
              <view class="time">
                <picker
                  :range="takeinRange"
                  range-key="name"
                  @change="takeinConfirmTime"
                >
                  <view class="picker">
                    {{ takeinRange[defaultSelector[0]]?.name || '立即用餐' }}
                  </view>
                </picker>
              </view>
            </view>
          </list-cell>
          <list-cell
            class="contact"
            last
            :hover="false"
            v-if="orderType == 'takein'"
          >
            <view
              class="flex-fill d-flex justify-content-between align-items-center"
            >
              <view class="title flex-fill">联系电话</view>
              <view class="time"
                ><input
                  class="text-right"
                  placeholder="请输入手机号码"
                  :value="member.mobile || ''"
                />
              </view>
              <button class="contact-tip font-size-sm">自动填写</button>
            </view>
          </list-cell>
        </template>
        <template v-if="orderType == 'takeout'">
          <list-cell>
            <view class="w-100 d-flex flex-column">
              <view
                class="d-flex align-items-center font-size-base text-color-base"
              >
                <view class="flex-fill">预计送达时间</view>
                <view class="mr-10">
                  <picker mode="time" @change="choiceTime" @cancel="cancelTime">
                    <view class="picker">
                      {{ defaultTime }}
                    </view>
                  </picker>
                </view>
              </view>
            </view>
          </list-cell>
        </template>
      </view>
      <!-- 购物车列表 begin -->
      <view class="section-2">
        <view class="cart d-flex flex-column">
          <list-cell last v-for="(item, index) in cart" :key="index">
            <view class="w-100 d-flex flex-column">
              <view class="d-flex align-items-center mb-10">
                <view
                  class="d-flex flex-fill justify-content-between align-items-center text-color-base font-size-lg"
                >
                  <image
                    style="width: 80rpx; height: 80rpx"
                    mode="aspectFill"
                    :src="item.image"
                  >
                  </image>
                </view>
                <view class="name-and-props overflow-hidden">
                  <view class="text-color-base font-size-lg">{{
                    item.name
                  }}</view>
                </view>
                <view
                  class="d-flex flex-fill justify-content-between align-items-center text-color-base font-size-lg"
                >
                  <view>x{{ item.number }}</view>
                  <view>￥{{ item.price }}</view>
                </view>
              </view>
              <view class="text-truncate font-size-base text-color-assist">{{
                item.valueStr
              }}</view>
            </view>
          </list-cell>
        </view>
        <list-cell last>
          <view class="flex-fill d-flex justify-content-end align-items-center">
            <view>
              总计￥{{ total }}
              <text v-if="orderType == 'takeout'"
                >,配送费￥{{ store.deliveryPrice || 0 }}</text
              >
              <text v-if="coupon.value">,￥-{{ coupon.value }}</text>
              ,实付
            </view>
            <view class="font-size-extra-lg font-weight-bold"
              >￥{{ amount }}</view
            >
          </view>
        </list-cell>
      </view>
      <!-- 购物车列表 end -->
      <view
        class="d-flex align-items-center justify-content-start font-size-sm text-color-warning"
        style="padding: 20rpx 0"
      >
      </view>
      <!-- 支付方式 begin -->
      <view class="payment">
        <list-cell last :hover="false">
          <text>支付方式</text>
        </list-cell>
        <!-- #ifdef MP-WEIXIN -->
        <list-cell last>
          <view
            class="d-flex align-items-center justify-content-between w-100"
            @click="setPayType('weixin')"
          >
            <view
              class="iconfont iconwxpay line-height-100 payment-icon"
              style="color: #7eb73a"
            ></view>
            <view class="flex-fill">微信支付</view>
            <view
              class="iconfont line-height-100 checkbox checked iconradio-button-on"
              v-if="payType == 'weixin'"
            >
            </view>
            <view
              class="iconfont line-height-100 checkbox iconradio-button-off"
              v-else
            ></view>
          </view>
        </list-cell>
        <!-- #endif -->
        <!-- #ifdef MP-ALIPAY -->
        <list-cell>
          <view
            class="d-flex align-items-center justify-content-between w-100"
            @click="setPayType('alipay')"
          >
            <view
              class="iconfont-yshop icon-alipay line-height-100 payment-icon"
              style="color: #07b4fd"
            >
            </view>
            <view class="flex-fill">支付宝</view>
            <view
              class="iconfont line-height-100 checkbox checked iconradio-button-on"
              v-if="payType == 'alipay'"
            ></view>
            <view
              class="iconfont line-height-100 checkbox iconradio-button-off"
              v-else
            ></view>
          </view>
        </list-cell>
        <!-- #endif -->
      </view>
      <!-- 支付方式 end -->
      <!-- 备注 begin -->
      <list-cell last @click="goToRemark">
        <view
          class="d-flex flex-fill align-items-center justify-content-between overflow-hidden"
          style="margin-bottom: 110rpx"
        >
          <view class="flex-shrink-0 mr-20">备注</view>
          <view class="text-color-primary flex-fill text-truncate text-right"
            >{{ form.remark || "点击填写备注" }}
          </view>
        </view>
      </list-cell>
      <!-- 备注 end -->
    </view>
    <!-- 付款栏 begin -->
    <view
      style="z-index: 1"
      class="w-100 pay-box position-fixed fixed-bottom d-flex align-items-center justify-content-between bg-white"
    >
      <view class="font-size-sm" style="margin-left: 20rpx">合计：</view>
      <view class="font-size-lg flex-fill">￥{{ amount }}</view>
      <view
        class="bg-primary h-100 d-flex align-items-center just-content-center text-color-white font-size-base"
        style="padding: 0 60rpx"
        @tap="debouncedSubmit"
        >付款
      </view>
    </view>
    <!-- 付款栏 end -->
    <modal
      :show="ensureAddressModalVisible"
      custom
      :mask-closable="false"
      :radius="'0rpx'"
      width="90%"
    >
      <view class="modal-content">
        <view class="d-flex justify-content-end">
          <image
            src="/static/images/pay/close.png"
            style="width: 40rpx; height: 40rpx"
            @tap="ensureAddressModalVisible = false"
          ></image>
        </view>
        <view
          class="d-flex just-content-center align-items-center"
          style="margin-bottom: 40px"
        >
          <view class="font-size-extra-lg text-color-base"
            >请再次确认下单地址</view
          >
        </view>
        <view
          class="d-flex font-size-base text-color-base font-weight-bold align-items-center justify-content-between mb-20"
        >
          <view>{{ address.realName }}</view>
          <view>{{ address.phone }}</view>
        </view>
        <view
          class="d-flex font-size-sm text-color-assist align-items-center justify-content-between mb-40"
        >
          <view style="max-width: 60%">{{
            address.address + address.detail
          }}</view>
          <button
            type="primary"
            size="min"
            plain
            class="change-address-btn"
            style="white-space: nowrap"
            @click="chooseAddress"
          >
            修改地址
          </button>
        </view>
        <button type="primary" class="pay_btn" @tap="debouncedPay">
          确认并付款
        </button>
      </view>
    </modal>
    <uv-toast ref="uToast"></uv-toast>
  </view>
</template>

<script setup>
import { computed, ref, onMounted, watch } from "vue";
import { useMainStore } from "@/store/store";
import { storeToRefs } from "pinia";
import { onHide, onLoad, onShow } from "@dcloudio/uni-app";
import { isWeixin } from "@/utils/util";
import debounce from "@/utils/debounce.js";

import { orderSubmit, payUnify } from "@/api/order";
import { couponCount } from "@/api/coupon";
import { ensurePlatformId } from '@/utils/platformId';

// 延迟初始化 store
let main = null;
const orderType = ref('takein');
const address = ref({});
const store = ref({});
const location = ref({});
const isLogin = ref(false);
const member = ref({});
const mycoupon = ref({});

// 在组件挂载后初始化 store
onMounted(() => {
  try {
    main = useMainStore();
    const storeRefs = storeToRefs(main);
    
    // 同步 store 数据到本地响应式变量
    orderType.value = storeRefs.orderType.value;
    address.value = storeRefs.address.value;
    store.value = storeRefs.store.value;
    location.value = storeRefs.location.value;
    isLogin.value = storeRefs.isLogin.value;
    member.value = storeRefs.member.value;
    mycoupon.value = storeRefs.mycoupon.value;
    
    // 监听 store 变化
    watch(storeRefs.address, (newAddress) => {
      address.value = newAddress;
    });
    
    watch(storeRefs.store, (newStore) => {
      store.value = newStore;
    });
    
    watch(storeRefs.member, (newMember) => {
      member.value = newMember;
    });
    
    watch(storeRefs.orderType, (newOrderType) => {
      orderType.value = newOrderType;
    });
    
    console.log('Store initialized successfully');
    console.log('Address data:', address.value);
    console.log('Store data:', store.value);
    console.log('Member data:', member.value);
    console.log('Order type:', orderType.value);
  } catch (error) {
    console.error('Error initializing store:', error);
  }
});
const active = ref(false);
const jsStr = ref("");
const cart = ref([]);
const form = ref({
  remark: "",
});
const leftSeconds = ref(0);

const ensureAddressModalVisible = ref(false);
const takeoutTIme = ref(false); // 外卖取餐时间picker
const paramsTime = ref({
  year: false,
  month: false,
  day: false,
  hour: true,
  minute: true,
  second: false,
});
const defaultTime = ref("00:00");
const takeinTIme = ref(false); // 到店自取时间selector
const takeinRange = ref([
  {
    name: "立即用餐",
    value: 0,
  },
  {
    name: "10分钟后",
    value: 10,
  },
  {
    name: "20分钟后",
    value: 20,
  },
  {
    name: "30分钟后",
    value: 30,
  },
  {
    name: "40分钟后",
    value: 40,
  },
  {
    name: "50分钟后",
    value: 50,
  },
]);
const defaultSelector = ref([0]);
const payType = ref("weixin"); // 付款方式
const coupons = ref(0); // 可用优惠券数量
const coupon = ref({}); // 选中的
const subscribeMss = ref({
  takein: "",
  takeout: "",
  takein_made: "",
  takeout_made: "",
}); // 微信订阅信息
const uToast = ref();

// 创建防抖函数
const debouncedSubmit = debounce(() => submit(), 500);
const debouncedPay = debounce(() => pay(), 500);

const total = computed(() => {
  return cart.value.reduce((acc, cur) => acc + cur.number * cur.price, 0);
});
const amount = computed(() => {
  let amount = cart.value.reduce((acc, cur) => acc + cur.number * cur.price, 0);
  // 加配送费
  if (
    store.value &&
    store.value.deliveryPrice !== undefined &&
    store.value.deliveryPrice !== null
  ) {
    amount += parseFloat(store.value.deliveryPrice);
  }

  // 减去优惠券
  if (mycoupon.value && mycoupon.value.hasOwnProperty("id")) {
    amount -= parseFloat(mycoupon.value.value);
  }
  return amount.toFixed(2);
});

onShow(() => {
  // 确保 store 已初始化后再获取数据
  if (main) {
    if (mycoupon.value) {
      coupon.value = mycoupon.value;
    }
    
    // 手动同步一次最新数据（防止 watch 没有触发）
    const storeRefs = storeToRefs(main);
    address.value = storeRefs.address.value;
    store.value = storeRefs.store.value;
    member.value = storeRefs.member.value;
    orderType.value = storeRefs.orderType.value;
    mycoupon.value = storeRefs.mycoupon.value;
  }
  
  let date = new Date(new Date().getTime() + 3600000); // 一个小时后
  let hour = date.getHours();
  let minute = date.getMinutes();
  if (hour < 10) {
    hour = "0" + hour;
  }
  if (minute < 10) {
    minute = "0" + minute;
  }
  defaultTime.value = hour + ":" + minute;

  console.log("member:", member.value);
  console.log("orderType =>", orderType.value);
  console.log("address =>", address.value);
  console.log("store =>", store.value);

  if (orderType.value == "takeout") {
    active.value = true;
  } else {
    active.value = false;
  }

  // getCoupons();

  let paytype = uni.getStorageSync("paytype");
  payType.value = paytype ? paytype : "weixin";
});
onHide(() => {
  subscribeMss.value = [];
  coupons.value = 0;
});
onLoad((option) => {
  cart.value = uni.getStorageSync("cart");
  if (option.remark) {
    form.value.remark = option.remark;
  }
  console.log("current orderType", orderType.value);
});

const getSubscribeMss = async () => {
  let data = [];
  if (data) {
    subscribeMss.value = data;
  }
};
// 更改支付方式
const setPayType = (paytype) => {
  // #ifdef MP-ALIPAY
  paytype = "alipay";
  // #endif

  // #ifdef MP-WEIXIN
  paytype = "weixin";
  // #endif

  payType.value = paytype || "";
  uni.setStorage({
    key: "paytype",
    data: payType.value,
  });
};
const getCoupons = async () => {
  //0=通用,1=自取,2=外卖
  let type = orderType.value == "takein" ? 1 : 2;
  let data = await couponCount({
    shop_id: store.value.id ? store.value.id : 0,
    type: type,
  });
  if (data) {
    coupons.value = data;
  }
};
// 选择时间
const choiceTime = (e) => {
  defaultTime.value = e.detail.value;
  takeoutTIme.value = false;
};
const cancelTime = (e) => {
  takeoutTIme.value = false;
};
// 到店自取-取消选择取餐时间
const takeinCancelTime = (e) => {
  takeinTIme.value = false;
};
// 到店自取-选择取餐时间
const takeinConfirmTime = (e) => {
  defaultSelector.value = [e.detail.value];
};
// 是否外卖开关
const takout = (value) => {
  let type = "takeout";
  if (value == false) {
    type = "takein";
  }
  if (main) {
    main.SET_ORDER_TYPE(type);
  }

  // 如果存在优惠券看看需不需要清除
  if (coupon.value.hasOwnProperty("type")) {
    //0=通用,1=自取,2=外卖
    if (coupon.value.type != 0) {
      if (coupon.value.type == 1 && orderType.value == "takeout") {
        coupon.value = {};
      }
      if (coupon.value.type == 2 && orderType.value == "takeint") {
        coupon.value = {};
      }
    }
  }
  subscribeMss.value = [];
  coupons.value = 0;
  // getCoupons();
};
const goToRemark = () => {
  uni.navigateTo({
    url: "/pages/components/pages/remark/remark?remark=" + form.value.remark,
  });
};
const chooseAddress = () => {
  uni.navigateTo({
    url: "/pages/components/pages/address/address?is_choose=true&scene=pay",
  });
};
const goToPackages = () => {
  let newamount = amount.value;
  let coupon_id = coupon.value.id ? coupon.value.id : 0;
  let type = orderType.value == "takein" ? 1 : 2;
  let shop_id = store.value.id;
  uni.navigateTo({
    url:
      "/pages/components/pages/packages/index?amount=" +
      newamount +
      "&coupon_id=" +
      coupon_id +
      "&shop_id=" +
      shop_id +
      "&type=" +
      type,
  });
};
const goToShop = () => {
  uni.navigateTo({
    url: `/pages/components/pages/shop/shop`,
  });
};


const submit = () => {
  // 需要配送地址的订单类型：外卖(takeout) 和 加盟商(franchisees)
  if (orderType.value == "takeout" || orderType.value == "franchisees") {
    // 检查是否选择了收货地址
    if (typeof address.value.id == "undefined" || !address.value.id) {
      uToast.value.show({
        message: "请选择收货地址",
        type: "error",
      });
      return;
    }

    // 外卖类型需要检查起送价
    if (orderType.value == "takeout" && store.value.min_price > total.value) {
      uToast.value.show({
        message: "本店外卖起送价为￥" + store.value.min_price,
        type: "error",
      });
      return;
    }

    pay();
  } else {
    // 其他类型（如 takein 到店自取）直接进入支付
    pay();
  }
};
const pay = async () => {
  let that = this;
  // #ifdef MP-WEIXIN
  await new Promise(function (revolve) {
    //订阅号信息id
    let subscribeMss = ["KBtfY9G1IWCzC6q-ZKo-Q-MmdP7aaF79nx0XFcBf3h4"];

    wx.showModal({
      title: "温馨提示",
      content: "为更好的促进您与商家的交流，小程序需要在您成交时向您发送消息",
      confirmText: "同意",
      cancelText: "拒绝",
      success: function (res) {
        if (res.confirm) {
          uni.requestSubscribeMessage({
            tmplIds: subscribeMss,
            complete(res) {
              console.log(res);
              revolve(true);
            },
          });
        } else {
          revolve(true);
        }
      },
    });
  });

  // #endif
  uni.showLoading({
    title: "加载中",
  });

  // 最后一次地址验证（安全检查）
  if (orderType.value == "takeout" || orderType.value == "franchisees") {
    if (!address.value.id) {
      uni.hideLoading();
      uToast.value.show({
        message: "请选择收货地址",
        type: "error",
      });
      return;
    }
  }

  let data = {
    orderType: orderType.value, // 购买类型:takein=自取,takeout=外卖
    addressId:
      orderType.value == "takeout" || orderType.value == "franchisees"
        ? address.value.id
        : 0, // 外卖配送地址
    shopId: store.value.id, // 店铺id
    mobile: member.value.mobile, // 联系电话
    gettime: takeinRange.value[defaultSelector.value[0]].value, // 取餐时间
    payType: payType.value, // 支付类型
    remark: form.value.remark, // 备注
    productId: [],
    spec: [],
    number: [],
    couponId: coupon.value.id ? coupon.value.id : 0, // 优惠券id
  };

  cart.value.forEach((item, index) => {
    data.productId.push(item.id);
    if (item.valueStr) {
      data.spec.push(item.valueStr?.replace(/,/g, "|"));
    }
    //data.spec.push(item.valueStr);
    data.number.push(item.number);
  });

  //console.log(data);
  let order = await orderSubmit(data);
  if (!order) {
    uni.hideLoading();
    return;
  }
  console.log("order:", order);
  // 输出订单支付相关日志信息
  console.log("order.orderId:", order.orderId);
  console.log("payType.value:", payType.value);
  console.log("amount.value:", amount.value);
  
  // 支付前确保平台ID存在
  if (payType.value === "weixin" || payType.value === "alipay") {
    const hasPlatformId = await ensurePlatformId('payment');
    if (!hasPlatformId) {
      uni.hideLoading();
      uni.showToast({
        title: '需要授权后才能支付',
        icon: 'none'
      });
      return;
    }
  }
  
  // 增加延迟，确保订单创建事务已提交
  console.log("等待订单创建完成...");
  await new Promise(resolve => setTimeout(resolve, 1000));
  
  if (payType.value == "weixin") {
    // 微信支付
    weixinPay(order);
  } else if (payType.value == "yue") {
    // 余额支付
    balancePay(order);
  } else if (payType.value == "alipay") {
    // 支付宝支付
    await aliPayWithRetry(order);
  }
  uni.hideLoading();
  return;
};
const balancePay = async (order) => {
  let from = "routine";
  let pay = await payUnify({
    uni: order.orderId,
    from: from,
    paytype: "yue",
  });

  uni.hideLoading();
  if (!pay) {
    return;
  }

  member.value.money -= amount.value;
  if (main) {
    main.SET_MEMBER(member.value);
  }
  uni.setStorageSync("cart", []);
  uni.switchTab({
    url: "/pages/order/order",
    fail(res) {
      console.log(res);
    },
  });
};
const weixinPay = async (order) => {
  let from = "routine";
  // #ifdef H5
  from = "h5";
  if (isWeixin()) {
    from = "wechat";
  }

  // #endif
  //let that = this;
  let data = await payUnify({
    uni: order.orderId,
    from: from,
    paytype: "weixin",
  });
  console.log("wxpay result:", data);
  if (!data) {
    uni.hideLoading();
    return;
  }
  if (data.trade_type == "MWEB") {
    // #ifdef H5
    // 微信外的H5
    console.log("data:", data);
    location.href = data.data;
    // #endif
    console.log("data1:", data);
  } else if (data.trade_type == "JSAPI") {
    console.log("param:", data);

    // #ifdef MP-WEIXIN
    uni.requestPayment({
      provider: "wxpay",
      timeStamp: data.data.timeStamp,
      nonceStr: data.data.nonceStr,
      package: data.data.package,
      signType: "MD5",
      paySign: data.data.paySign,
      success: function (res) {
        uni.setStorageSync("cart", []);
        // 此处弹出持续5秒的获取支付结果的弹出框
        uni.showToast({
          title: "获取支付结果...",
          icon: "loading",
          duration: 5000,
        });
        setTimeout(() => {
          uni.switchTab({
            url: "/pages/order/order",
          });
        }, 5000);
      },
      fail: function (err) {
        console.log("微信支付失败:" + JSON.stringify(err));
        uni.hideLoading();
        
        // 处理用户取消支付的情况
        if (err.errMsg && err.errMsg.includes('requestPayment:fail cancel')) {
          // 用户主动取消支付，跳转到订单详情页
          console.log('用户取消支付，跳转到订单详情页');
          uni.navigateTo({
            url: `/pages/components/pages/orders/detail?id=${order.orderId}`,
            fail: (navErr) => {
              console.error('跳转订单详情页失败:', navErr);
              // 如果跳转失败，回到订单列表页
              uni.switchTab({
                url: "/pages/order/order"
              });
            }
          });
        } else {
          // 其他支付错误，显示错误信息
          uni.showToast({
            title: '支付失败，请重试',
            icon: 'none'
          });
        }
      },
    });
    // #endif
  } else if (data.trade_type == "W-JSAPI") {
    //公众号支付
  } else if (data.trade_type == "APP") {
  }
};

// 带重试机制的支付宝支付方法
const aliPayWithRetry = async (order, retryCount = 0) => {
  const maxRetries = 2; // 最大重试次数
  
  try {
    await aliPay(order);
  } catch (error) {
    console.error(`支付宝支付失败 (尝试 ${retryCount + 1}/${maxRetries + 1}):`, error);
    
    // 如果是订单不存在的错误且还有重试次数
    if (error.message && error.message.includes('订单不存在') && retryCount < maxRetries) {
      console.log(`等待 ${(retryCount + 1) * 1000}ms 后重试...`);
      await new Promise(resolve => setTimeout(resolve, (retryCount + 1) * 1000));
      return await aliPayWithRetry(order, retryCount + 1);
    } else {
      // 重试次数用完或其他错误，直接抛出
      throw error;
    }
  }
};

const aliPay = async (order) => {
  console.log('开始支付宝支付流程');
  console.log('订单信息:', order);
  console.log('用户信息:', member.value);
  
  // #ifdef MP-ALIPAY
  try {
    // 支付宝小程序支付
    let from = 'alipay';
    
    // 检查必要的参数
    if (!order || !order.orderId) {
      console.error('订单信息缺失:', order);
      uni.showToast({
        title: '订单信息错误',
        icon: 'none'
      });
      return;
    }
    
    console.log('发起支付请求 - 订单号:', order.orderId, '支付类型:', 'alipay', '来源:', from);
    
    let alipayData = await payUnify({
      uni: order.orderId,
      from: from,
      paytype: 'alipay',
    });

    console.log('alipay result:', alipayData);

    if (!alipayData) {
      uni.hideLoading();
      console.error('支付接口返回数据异常:', alipayData);
      uni.showToast({
        title: '获取支付参数失败',
        icon: 'none'
      });
      return;
    }

    // 根据后端实际返回的数据结构处理
    let orderInfo = '';
    let tradeType = 'JSAPI';
    
    if (alipayData.body && alipayData.success) {
      // 后端返回格式：{body: "支付宝订单字符串", success: true}
      orderInfo = alipayData.body;
      tradeType = 'JSAPI';
      console.log('使用 body 字段作为支付参数');
    } else if (alipayData.data && alipayData.trade_type) {
      // 标准格式：{data: "支付宝订单字符串", trade_type: "JSAPI"}
      orderInfo = alipayData.data;
      tradeType = alipayData.trade_type;
      console.log('使用 data 字段作为支付参数');
    } else if (alipayData.data) {
      // 兼容格式：{data: "支付宝订单字符串"} (无 trade_type)
      orderInfo = alipayData.data;
      tradeType = 'JSAPI';
      console.log('使用 data 字段作为支付参数 (默认 JSAPI)');
    } else if (typeof alipayData === 'string') {
      // 直接字符串格式
      orderInfo = alipayData;
      tradeType = 'JSAPI';
      console.log('使用字符串作为支付参数');
    } else {
      uni.hideLoading();
      console.error('支付参数格式不正确:', alipayData);
      uni.showToast({
        title: '支付参数格式错误',
        icon: 'none'
      });
      return;
    }

    // 验证支付参数格式
    if (typeof orderInfo !== 'string' || !orderInfo) {
      console.error('支付参数格式错误:', typeof orderInfo, orderInfo);
      uni.showToast({
        title: '支付参数格式错误',
        icon: 'none'
      });
      return;
    }

    console.log('最终支付参数:', orderInfo);
    console.log('交易类型:', tradeType);

    if (tradeType === 'JSAPI' || tradeType === 'JSAPI_PAY') {
      // 支付宝小程序支付
      console.log('调用支付宝支付接口');
      uni.requestPayment({
        provider: 'alipay',
        orderInfo: orderInfo, // 支付宝订单信息
        success: function(res) {
          console.log('支付成功:', res);
          uni.setStorageSync("cart", []);
          // 此处弹出持续5秒的获取支付结果的弹出框
          uni.showToast({
            title: "支付成功",
            icon: "success",
            duration: 2000,
          });
          setTimeout(() => {
            uni.switchTab({
              url: "/pages/order/order",
            });
          }, 2000);
        },
        fail: function(err) {
          console.error('支付宝支付失败:', err);
          uni.hideLoading();
          
          // 详细的错误处理
          let errorMsg = '支付失败';
          let showDeveloperTip = false;
          let userCanceled = false;
          
          if (err.memo && err.memo.includes('API 代理')) {
            errorMsg = '开发环境配置问题';
            showDeveloperTip = true;
          } else if (err.resultCode === '4000') {
            errorMsg = '支付环境配置错误';
            showDeveloperTip = true;
          } else if (err.resultCode === '6001') {
            errorMsg = '用户取消支付';
            userCanceled = true;
          } else if (err.resultCode === '6002') {
            errorMsg = '网络连接出错';
          } else if (err.resultCode === '99999') {
            errorMsg = '系统繁忙，请稍后再试';
          }
          
          // 处理用户取消支付的情况
          if (userCanceled) {
            console.log('用户取消支付，跳转到订单详情页');
            uni.navigateTo({
              url: `/pages/components/pages/orders/detail?id=${order.orderId}`,
              fail: (navErr) => {
                console.error('跳转订单详情页失败:', navErr);
                // 如果跳转失败，回到订单列表页
                uni.switchTab({
                  url: "/pages/order/order"
                });
              }
            });
          } else if (showDeveloperTip) {
            // 显示开发者提示
            uni.showModal({
              title: '开发环境提示',
              content: '请在支付宝开发者工具中：\n1. 点击右上角"详情"\n2. 选择"项目配置"\n3. 勾选"启用API代理"\n4. 勾选"不校验合法域名"',
              confirmText: '我知道了',
              showCancel: false
            });
          } else {
            uni.showToast({
              title: errorMsg,
              icon: 'none',
              duration: 3000
            });
          }
        }
      });
    } else {
      console.error('Unsupported trade type for Alipay:', tradeType);
      uni.showToast({
        title: '不支持的支付类型: ' + tradeType,
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('支付宝支付异常:', error);
    uni.hideLoading();
    
    // 检查是否是接口返回的业务错误
    if (error.message && error.message.includes('订单不存在')) {
      uni.showModal({
        title: '支付失败',
        content: '订单不存在或状态异常，请重新下单',
        confirmText: '重新下单',
        cancelText: '取消',
        success: function(res) {
          if (res.confirm) {
            // 返回购物车重新下单
            uni.navigateBack();
          }
        }
      });
    } else {
      uni.showToast({
        title: '支付异常，请重试',
        icon: 'none'
      });
    }
  }
  // #endif
  
  // #ifdef H5
  //let that = this;
  if (isWeixin()) {
    uni.showToast({
      title: "请普通浏览器打开进行支付宝支付~",
      icon: "none",
    });
    return;
  }
  let h5Data = await payUnify({
    uni: order.orderId,
    from: "h5",
    paytype: "alipay",
  });

  console.log("data:", h5Data.data);
  // 支付宝支付，这里只要提交表单
  let form = h5Data.data;
  const div = document.createElement("formdiv");
  div.innerHTML = form;
  document.body.appendChild(div);
  //document.forms[0].setAttribute('target', ' self');
  document.forms[0].submit();
  //div.remove();
  // #endif
};
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
}

.arrow {
  width: 50rpx;
  height: 50rpx;
  position: relative;
  margin-right: -10rpx;
}

.location {
  .store-name {
    font-size: $font-size-lg;
  }

  .iconfont {
    font-size: 50rpx;
    line-height: 100%;
    color: $color-primary;
  }
}

.section-1 {
  margin-bottom: 30rpx;

  .contact {
    .contact-tip {
      margin-left: 10rpx;
      border: 2rpx solid $color-primary;
      padding: 6rpx 10rpx;
      color: $color-primary;
    }
  }
}

.section-2 {
  .name-and-props {
    width: 65%;
  }
}

.payment {
  margin-bottom: 30rpx;

  .disabled {
    color: $text-color-grey;
  }

  .payment-icon {
    font-size: 44rpx;
    margin-right: 10rpx;
  }

  .checkbox {
    font-size: 36rpx;
    margin-left: 10rpx;
  }

  .checked {
    color: $color-primary;
  }
}

.pay-box {
  box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);
  height: 100rpx;
}

.modal-content {
  .change-address-btn {
    line-height: 2;
    padding: 0 1em;
  }

  .pay_btn {
    width: 100%;
    border-radius: 50rem !important;
    line-height: 3;
  }
}

.choice {
  background-color: $bg-color-grey;
  border-radius: 38rpx;
  display: flex;
  align-items: center;
  font-size: $font-size-sm;
  padding: 0 38rpx;
  color: $text-color-assist;

  .dinein,
  .takeout {
    width: 50%;
    position: relative;
    display: flex;
    align-items: center;

    &.active {
      padding: 14rpx 38rpx;
      color: #ffffff;
      background-color: $color-primary;
      border-radius: 38rpx;
    }
  }

  .takeout {
    margin-left: 20rpx;
    height: 100%;
    flex: 1;
    padding: 14rpx 0;
  }
}
</style>